package com.lanou3g.Code0523.permission;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/23;
 * Otherwise, I don't know who created it either
 */

@WebFilter(filterName = "AdminFilter",urlPatterns = "/admin/*")
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //判断是否是管理员登录
        System.out.println("admin");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null && user.isAdmin()){
            // 是管理员登录
            chain.doFilter(request, response);
        }else {
            // 不是管理员或没有登录
            resp.sendRedirect("/login.html");
        }

    }

    @Override
    public void destroy() {

    }
}
